import account from '@/assets/account.png';
import company from '@/assets/company.png';
import house from '@/assets/house.png';
import mortgage from '@/assets/mortgage.png';
import privateImg from '@/assets/private.png';
import { getLocale, history } from 'umi';
export const useUrlParams = (keyWords: string, href = window.location.href) => {
  // 从占位符开始截取路由（不包括占位符）
  const query = href.substring(href.indexOf('?') + 1);
  // 根据 & 切割字符串
  const vars = query.split('&');
  for (let i = 0; i < vars.length; i++) {
    const pair = vars[i].split('=');
    // 根据指定的参数名去筛选参数值
    if (pair[0] == keyWords) {
      return pair[1];
    }
  }
  return '';
};

export const copy = (text: string, cb?: () => void) => {
  const transfer = document.createElement('input');
  document.body.appendChild(transfer);
  transfer.value = text;
  transfer.select();
  if (document.execCommand('copy')) {
    document.execCommand('copy');
  }
  document.body.removeChild(transfer);
  cb?.();
};

// 小写数字转换为大写
export const numberToUpperCase = (num: number) => {
  const units = ['', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  const decimals = ['', '十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千', '兆'];

  const str = num.toString();
  let result = '';

  for (let i = 0; i < str.length; i++) {
    const num = parseInt(str.charAt(i));
    const unit = units[num];
    const decimal = decimals[str.length - i - 1];

    result += decimal ? unit + decimal : unit;
  }

  return result;
};
export const numberToEnglish = (num: number) => {
  const arr = ['First', 'Second', 'Third', 'Fourth', 'Fifth'];
  return arr[num];
};
//  obj转成label,value模式
export const getOptions = (list: any, label: string = 'name', val: string = 'value') => {
  if (Array.isArray(list)) {
    const newList = (list || []).map((item) => {
      return {
        ...item,
        value: item[val],
        label: item[label],
      };
    });
    return newList;
  } else {
    const cList = Object.keys(list || {}) || [];
    const newList =
      (cList.length > 0 &&
        cList.map((item) => {
          return {
            label: list[item].text || list[item],
            value: item,
            ...list[item],
          };
        })) ||
      [];
    return newList;
  }
};

export const phoneFormatter = (phone: string) => {
  const newPhone = phone?.toString();
  return newPhone ? newPhone?.replace(newPhone?.substring(3, 7), '****') : '';
};

export const formatNumber = (value: number | string, needSign = true) => {
  return `${needSign ? '$' : ''}${value?.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')}`;
};

export const getImgUrl = (list: any[]) => {
  return list?.length > 0
    ? list
        .filter((item) => item.url)
        .map((item) => {
          return item.url;
        })
        .toString()
    : '';
};
// 格式化后端给的图片数据
export const formatImgItem = (list: string) => {
  return list
    ? list.split(',').map((item: string) => {
        return {
          uid: item,
          name: item.split('/')[item.split('/').length - 1],
          status: 'done',
          url: item,
        };
      })
    : [];
};
export const keyList = [
  'idCard',
  'addressProof',
  'bankMonthlyStatement',
  'workProof',
  'creditProof',
  'estateProof',
  'vehicleProof',
  'stockProof',
  'insuranceProof',
  'cryptocurrencyProof',
  'otherProof',
];

// 设置cookie
export function setCookie(cname: string, cvalue: string, exdays = 100000000) {
  const d = new Date();
  d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
  const expires = 'expires=' + (d as any).toGMTString();
  document.cookie = cname + '=' + cvalue + '; ' + expires;
}

// 获取cookie
export function getCookie(cname: string) {
  const name = cname + '=';
  const ca = document.cookie.split(';');
  for (let i = 0; i < ca.length; i++) {
    const c = ca[i].trim();
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return '';
}

export const handleWhatsApp = (phone: string) => {
  window.open('https://wa.me/852' + phone, '_blank');
};
export const donwLoadGoogle = () => {
  window.open('');
};
export const donwLoad = () => {
  window.open('');
};

export const donwLoadApp = () => {
  window.open('');
};
export const donwLoadFile = (response: any) => {
  const url = URL.createObjectURL(response.data);
  const a = document.createElement('a');
  a.style.display = 'none';
  a.href = url;
  if (response?.headers['content-disposition']) {
    a.download = decodeURIComponent(response?.headers['content-disposition'].split('filename=')[1]);
  }
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
};
const renderLangUrl = () => {
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const lang = useUrlParams('lang') || getLocale();
  switch (lang) {
    case 'zh-TW':
      return '';
    case 'en-US':
      return '/en';
  }
};

export const jumpUrl = (url: string, state = {}) => {
  const hasParams = url.split('?').length > 1;
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const lang = useUrlParams('lang') || getLocale();

  const newUrl = !hasParams ? `${url}?lang=${lang}` : `${url}&lang=${lang}`;
  history.push(`${renderLangUrl()}${newUrl}`, state);
};
export const getNewUrl = (url: string) => {
  const hasParams = url.split('?').length > 1;
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const lang = useUrlParams('lang') || getLocale();

  const newUrl = !hasParams ? `${url}?lang=${lang}` : `${url}&lang=${lang}`;
  return `${renderLangUrl()}${newUrl}`;
};
export const openUrl = (url: string) => {
  const hasParams = url.split('?').length > 1;
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const lang = useUrlParams('lang') || getLocale();

  const newUrl = !hasParams ? `${url}?lang=${lang}` : `${url}&lang=${lang}`;

  window.open(`${renderLangUrl()}${newUrl}`);
};

export const langList = [
  {
    lang: 'zh-TW',
    label: '繁體',
    // logo: cnLogo,
    icon: ' ',
  },
  {
    lang: 'en-US',
    label: 'EN',
    // logo: cnLogo,
    icon: ' ',
  },
];

export const replaceQueryParam = (uri: string, key: string, value: string) => {
  const re = new RegExp('([?&])' + key + '=.*?(&|$)', 'i');
  const separator = uri.indexOf('?') !== -1 ? '&' : '?';
  if (uri.match(re)) {
    return uri.replace(re, '$1' + key + '=' + value + '$2');
  } else {
    return uri + separator + key + '=' + value;
  }
};

export const productList = [
  { word: 'home.private', icon: privateImg, key: '1', bottomWord: 'home.private_des' },
  { word: 'home.account', icon: account, key: '2', bottomWord: 'home.account_des' },
  { word: 'home.house', icon: house, key: '3', bottomWord: 'home.house_des' },
  { word: 'home.loan', icon: mortgage, key: '4', bottomWord: 'home.loan_des' },
  { word: 'home.company', icon: company, key: '5', bottomWord: 'home.company_des' },
];

export const validIdNumber = (idNumber: string) => {
  // 此处只处理英文括号
  const card = idNumber.replace(/[\(\)]/g, '').replace(/\s/g, '');
  let sum = 0;

  // 检查长度是否为 8
  if (card.length !== 8) {
    return false;
  }

  // 转换第一个字母并乘以加权因子
  sum = (card.substring(0, 1).toUpperCase().charCodeAt(0) - 64) * 8;

  const mid = card.substring(1, 7);
  const end = card.substring(7, 8);
  const chars = mid.split('');
  let iflag = 7;

  // 计算中间部分的加权和
  for (const c of chars) {
    sum += parseInt(c) * iflag;
    iflag--;
  }

  // 处理最后一位
  if (end.toUpperCase() === 'A') {
    sum += 10;
  } else {
    sum += parseInt(end);
  }

  // 检查是否能被 11 整除
  return sum % 11 === 0;
};
